package com.tunghuynh.game.st_avoidball;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.tunghuynh.hpbd.Global;
import com.tunghuynh.hpbd.R;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AvoidBall extends Activity implements OnTouchListener {
	DrawPanel dp;
	boolean holdBall = false;
	boolean isStarted = false;
	private Paint paintMyBall = new Paint();
	private Paint paintObsBall = new Paint();
	private Ball[] lstObsBall = new Ball[50];
	private Ball myBall;
	private static TextView tvRemainTime, tvMsg;
	private int time = 22;
	private MediaPlayer mp, mpHit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_avoid_ball);
		tvRemainTime = (TextView) findViewById(R.id.txtRemain);
		tvMsg = (TextView) findViewById(R.id.txtMsg);
		tvMsg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Global.game1IsPassed) {
					finish();
				} else {
					isStarted = true;
					countDownTime(22);
					tvMsg.setVisibility(View.INVISIBLE);
				}
			}
		});
		init(25, 400, 700);
		
		mp = MediaPlayer.create(AvoidBall.this, R.raw.hpbd);
		mpHit = MediaPlayer.create(AvoidBall.this, R.raw.hit);
		
		msbox("Tip",
				"Hãy di chuyển quả bóng màu Xanh để tránh không bị va chạm với các quả bóng màu khác trong vòng 22 giây.");
		dp = new DrawPanel(this);
		dp.setOnTouchListener(this);

		paintMyBall.setColor(Color.GREEN);
		// paintLine.setStyle(Paint.Style.STROKE);
		paintMyBall.setStrokeWidth(3);

		paintMyBall.setTextSize(25);
		// paintMyBall.setFakeBoldText(true);
		// paintMyBall.set

		paintObsBall.setColor(Color.RED);
		paintObsBall.setTextSize(25);
//		paintObsBall.setShader(new RadialGradient(10, 10, 100 / 3, Color.RED,
//				Color.YELLOW, Shader.TileMode.MIRROR));

		LinearLayout fl = (LinearLayout) findViewById(R.id.layoutCanvas1);
		fl.addView(dp);

	}

	@Override
	protected void onPause() {
		super.onPause();
		dp.pause();
		mp.stop();
	}

	@Override
	protected void onResume() {
		super.onResume();
		dp.resume();
		mp.start();
	}

	Timer timer;

	private void countDownTime(int start) {
		time = start;
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {// Cho timer chay neenf ung dung
					// @Override
					public void run() {
						// TODO Auto-generated method stub
						tvRemainTime.setText("Remain: " + (time--) + "s");
						if (time < 0) {
							isStarted = false;
							Global.game1IsPassed = true;
							tvMsg.setText("You Passed!");
							tvMsg.setVisibility(View.VISIBLE);
							timer.cancel();
						}
					}
				});
			}
		}, 0, 1 * 1000);
	}

	public void msbox(String title, String msg) {
		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setTitle(title);
		dlgAlert.setMessage(msg);
		dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// finish();
			}
		});
		dlgAlert.setCancelable(true);
		dlgAlert.create().show();
	}

	private void init(int ballNum, int width, int height) {
		holdBall = false;
		isStarted = false;
		Global.game1IsPassed = false;
		myBall = new Ball(width / 2, height / 2, 30);
		Random rand = new Random();
		for (int i = 0; i < ballNum; i++) {
			int r = rand.nextInt(10) + 30;// 30->40
			float x = rand.nextInt(width - r - 2) + r + 1;// r->width
			float y = rand.nextInt(height - r - 2) + r + 1;// r->height
			float jumpx = rand.nextInt(3) + 2;// 3->6
			float jumpy = rand.nextInt(3) + 2;// 3->6
			boolean sign = rand.nextBoolean();
			if (!sign) {
				jumpx *= -1;
				jumpy *= -1;
			}
			lstObsBall[i] = new Ball(x, y, r, jumpx, jumpy);
		}
	}
	
	private boolean touchBall(Ball b1, Ball b2) {
		float distance = (float) Math.sqrt(Math.pow(b1.X - b2.X, 2)
				+ Math.pow(b1.Y - b2.Y, 2));
		float R = b1.R + b2.R;
		if (distance <= R)
			return true;
		return false;
	}

	private void runBall(Canvas canvas, int i) {
		if (isStarted) {
			if (touchBall(lstObsBall[i], myBall)) {
				isStarted = false;
				mpHit.start();
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						tvMsg.setText("Play again");
						tvMsg.setVisibility(View.VISIBLE);
					}
				});
				timer.cancel();
			}
			if (lstObsBall[i].X >= canvas.getWidth() - lstObsBall[i].R
					|| lstObsBall[i].X < 0 + lstObsBall[i].R)
				lstObsBall[i].jumpX = -lstObsBall[i].jumpX;
			if (lstObsBall[i].Y >= canvas.getHeight() - lstObsBall[i].R
					|| lstObsBall[i].Y < 0 + lstObsBall[i].R)
				lstObsBall[i].jumpY = -lstObsBall[i].jumpY;
			lstObsBall[i].X += lstObsBall[i].jumpX;
			lstObsBall[i].Y += lstObsBall[i].jumpY;

		}
		canvas.drawCircle(lstObsBall[i].X, lstObsBall[i].Y, lstObsBall[i].R,
				paintObsBall);
		canvas.drawText((i + 1) + "", lstObsBall[i].X - lstObsBall[i].R / 2,
				lstObsBall[i].Y + lstObsBall[i].R / 2, paintMyBall);
	}

	public boolean onTouch(View v, MotionEvent me) {
		if (me.getAction() == MotionEvent.ACTION_DOWN) {
			Ball teamp = new Ball(me.getX(), me.getY(), 1);
			if (touchBall(teamp, myBall))
				holdBall = true;
		}
		if (me.getAction() == MotionEvent.ACTION_UP) {
			holdBall = false;
		}
		if (me.getAction() == MotionEvent.ACTION_MOVE && holdBall) {
			myBall.X = me.getX();
			myBall.Y = me.getY();
		}
		return true;
	}

	@SuppressLint("WrongCall")
	public class DrawPanel extends SurfaceView implements Runnable {
		Thread t = null;
		SurfaceHolder holder;
		boolean isItOk = false;

		public DrawPanel(Context context) {
			super(context);
			holder = getHolder();
		}

		public void run() {
			while (isItOk == true) {
				if (!holder.getSurface().isValid()) {
					continue;
				}
				Canvas c = holder.lockCanvas();
				c.drawARGB(255, 0, 0, 0);
				onDraw(c);
				holder.unlockCanvasAndPost(c);
			}
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawCircle(myBall.X, myBall.Y, myBall.R, paintMyBall);

			runBall(canvas, 0);
			runBall(canvas, 1);
			runBall(canvas, 2);
			runBall(canvas, 3);
			runBall(canvas, 4);
			runBall(canvas, 5);
			runBall(canvas, 6);
			runBall(canvas, 7);
			runBall(canvas, 8);
			runBall(canvas, 9);

			runBall(canvas, 10);
			runBall(canvas, 11);
			runBall(canvas, 12);
			runBall(canvas, 13);
			runBall(canvas, 14);
			runBall(canvas, 15);
			runBall(canvas, 16);
			runBall(canvas, 17);
			runBall(canvas, 18);
			runBall(canvas, 19);
			runBall(canvas, 20);
			runBall(canvas, 21);

		}

		public void pause() {
			isItOk = false;
			while (true) {
				try {
					t.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				break;
			}
			t = null;
		}

		public void resume() {
			isItOk = true;
			t = new Thread(this);
			t.start();

		}
	}
}
